<!DOCTYPE html>
<html>
<head>
    <title>商城首页</title>
    <link rel="stylesheet" type="text/css" href="/css/styles.css">
    <script src="/js/scripts.js" defer></script>
</head>
<body>
    <header>
        <h1>商城首页</h1>
        <div class="user-info">
            <a id="user-link" href="/auth/login">登录</a>
        </div>
    </header>

    <section>
        <h2>商品列表</h2>
        <ul id="product-list">
        </ul>
    </section>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            fetch('/products')
                .then(response => response.json())
                .then(products => {
                    const productList = document.getElementById('product-list');
                    products.forEach(product => {
                        const li = document.createElement('li');
                        li.innerHTML = `
                            ${product.name} - ￥${product.price}
                            <button onclick="addToCart(${product.id})">加入购物车</button>
                        `;
                        productList.appendChild(li);
                    });
                });
            fetch('/auth/user-info')
                .then(response => response.json())
                .then(user => {
                    if (user) {
                        const userLink = document.getElementById('user-link');
                        userLink.textContent = user.username;
                        userLink.href = '/user';
                    }
                });
        });
        function addToCart(productId) {
            fetch('/cart/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ productId })
            }).then(response => {
                if (response.ok) {
                    alert('商品已加入购物车');
                } else {
                    alert('请先登录');
                    window.location.href = '/auth/login';
                }
            });
        }
    </script>
</body>
</html>